import { defineStore } from "pinia";

import {
    getUserDataApi,
    addUserDataApi,
    updateUserDataApi,
    delUserDataApi,
    downloadModelApi,
    uploadModelApi
} from '@/Api/Doctor'
import EventBus from "@/utils/EventBus";

import { useCommon } from "./Common";
import { downloadFileData } from "@/utils/downloadFile";
const CommonStore = useCommon();
const isDev = import.meta.env.MODE == 'development'

export const useDoctor = defineStore('Doctor', {
    state: (): DoctorState => {
        return {
            loading: false,
            searchForm: {
                name: '',
                sex: null,
                serials: [],
                department: '',
                illArea: '',
                departmentWard: [],

                current: 1,
                pageNo: 1,
                pageSize: 20,
                total: 0,
                pageSizeOptions: ['20', '30', '50', '100'],
                showSizeChanger: true,
                showTotal(total: number) { return `共${total}条` },
                onChange(pageNo: number, pageSize: number) {
                    this.current = pageNo
                    this.pageNo = pageNo
                    this.pageSize = pageSize
                }
            },
            addForm: {} as Doctor,
            editForm: {} as Doctor,
            tableData: [],
            modelForm: {
                multipartFile: []
            },
        }
    },
    actions: {
        async getUserData() {
            this.loading = true
            const valueToLabelMap = CommonStore.deviceOptions.reduce((acc, obj) => {
                acc[obj.value] = obj.label;
                return acc;
            }, {} as any);

            if (this.searchForm.departmentWard != undefined && this.searchForm.departmentWard.length == 1) {
                this.searchForm.department = this.searchForm.departmentWard[0]
                this.searchForm.illArea = null
            } else if (this.searchForm.departmentWard != undefined && this.searchForm.departmentWard.length == 2) {
                this.searchForm.department = this.searchForm.departmentWard[0]
                this.searchForm.illArea = this.searchForm.departmentWard[1]
            } else {
                if (CommonStore.department != '检验科') {
                    this.searchForm.department = CommonStore.department
                    this.searchForm.illArea = CommonStore.illArea
                } else {
                    this.searchForm.department = ''
                    this.searchForm.illArea = ''
                }
            }
            try {
                const data = await getUserDataApi(this.searchForm) as any
                if (data) {
                    this.tableData = data.nurse
                    this.tableData.forEach((item, index) => {
                        item.index = (this.searchForm.pageNo! - 1) * this.searchForm.pageSize! + index + 1
                        item.deviceNames = item.serials.map((value: any) => valueToLabelMap[value]).toString();
                        item.departmentWard = item.illArea ? [item.department, item.illArea] : [item.department]
                    })
                    this.searchForm.total = data.total[0].total
                }
            }
            finally {
                this.loading = false
            }
        },
        async addUserData() {
            this.addForm.department = this.addForm.departmentWard[0]
            this.addForm.illArea = this.addForm.departmentWard[1]
            const data = await addUserDataApi(this.addForm)
            if (!data) {
                this.getUserData()
                EventBus.emit('AddSuccess')
            }
        },
        async editUserData() {
            // if (this.editForm.departmentWard.includes('-') && typeof this.editForm.departmentWard === 'string') {
            //     this.editForm.departmentWard = this.editForm.departmentWard.split('-')
            // }
            console.log(this.editForm);
            this.editForm.department = this.editForm.departmentWard[0]
            this.editForm.illArea = this.editForm.departmentWard[1]
            const data = await updateUserDataApi(this.editForm)
            if (!data) {
                this.getUserData()
                EventBus.emit('UpdateSuccess')
            }
        },
        async delUserData(info: string) {
            const data = await delUserDataApi({ info })
            if (!data) {
                this.getUserData()
                EventBus.emit('DeleteSuccess')
            }
        },
        async downloadModel() {
            // const data = await downloadModelApi()
            const data = await (await fetch(isDev ? '/医护管理模板.xlsx' : "/closet/医护管理模板.xlsx")).blob()
            if (data) {
                downloadFileData(data, "医护管理模板.xlsx")
            }
        },
        async uploadModel() {
            const formData = new FormData()
            for (const key in this.modelForm) {
                if (key == 'multipartFile') {
                    formData.append(key, this.modelForm[key][0])
                }
            }
            try {
                const data = await uploadModelApi(formData) as any
                if (data) {
                    downloadFileData(data, "医护管理模板注册情况.xlsx")
                    EventBus.emit('UploadSuccess')
                    this.getUserData()
                }
            } finally { }
        },
    }
})